package com.fearless.test02;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class House {

    private int count=0;
    Lock lock=new ReentrantLock();
    Condition condition = lock.newCondition();


    void consume() throws InterruptedException {

        lock.lock();

        try {
            while (count==0){
                condition.await();
            }

            count--;
            System.out.println("当前库存是"+count+Thread.currentThread().getName()+"进行消费");
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }

    void produce() throws InterruptedException {

        lock.lock();

       try{
           while (count>0){
               condition.await();
           }

           count++;
           System.out.println("当前库存是"+count+Thread.currentThread().getName()+"进行生产");
           condition.signalAll();
       }catch (Exception e){
           e.printStackTrace();
       }finally {
           lock.unlock();
       }

    }
}
class Test4{
    public static void main(String[] args) {
        House house=new House();

        new Thread(()->{
            try {
                for (int i = 0; i <20 ; i++) {
                    house.produce();
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"生产者").start();



        new Thread(()->{
            try {
                for (int i = 0; i <20 ; i++) {
                    house.consume();

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"消费者").start();

    }

}